﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using SundStudent.ModelLayer;

// 2012.12.03 Kis Boisen Hansen


namespace SundStudent.DBLayer
{
    public class DBModul

    {
        private SqlCommand dbCmd = null;

        public DBModul()
        {
        }

        public Modul FindModul(int nr)
        {
            string sql = @"select nr, beskrivelse from modul " +
                           " where nr  = '" + nr; 

            Console.WriteLine("sql stmt = " + sql);

           dbCmd = DBConnection.GetDbCommand(sql);

            IDataReader dbReader;
            dbReader = dbCmd.ExecuteReader();

            Modul modulObj;

            if (dbReader.Read())
            {
                try
                {
                    Console.WriteLine("antal felter " + dbReader.FieldCount);
                    modulObj = new Modul();
                    modulObj.Modulnr = Convert.ToInt32(dbReader["nr"].ToString());
                    modulObj.Navn = dbReader["beskrivelse"].ToString();
                              
                    Console.WriteLine("Modul objekt oprettet");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Modul objekt ikke oprettet korrekt");
                    modulObj = null;
                }


            }

            else
            {
                modulObj = null;
            }
            dbReader.Close();
            DBConnection.Close();
            return modulObj;
        }


        public List<Modul> GetAllModules()
        {
            List<Modul> returnList = new List<Modul>();
            string sql = "select nr, beskrivelse "
                       + " from modul";

            SqlCommand dbCmd = DBConnection.GetDbCommand(sql);

            IDataReader dbReader;
            dbReader = dbCmd.ExecuteReader();

            Modul modulObj;

            while (dbReader.Read())
            {
                
                modulObj = new Modul();
                modulObj.Modulnr = Convert.ToInt32(dbReader["nr"].ToString());
                modulObj.Navn = dbReader["beskrivelse"].ToString();
                returnList.Add(modulObj);
            }
            DBConnection.Close();
            return returnList;

        }
    }
}

